import axios from "axios";
import router from "./router";
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = "http://localhost:8081"

const request = axios.create({
	timeout: 5000,
	headers: {
		'Content-Type': "application/json; charset=utf-8"
	}
})

request.interceptors.request.use(config => {
	config.headers['Authorization'] = localStorage.getItem("token")
	// config.headers['Authorization'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI2NjY2NjYiLCJpYXQiOjE2MzIxNTg0MjAsImV4cCI6MTYzMjc2MzIyMH0.un7lEswVxf0fxpeuI7FwWBiRzwQUh2Z7hinkLlTcU9oPt2p-XhsuSs3IcSL4YGVec-GlNtm9wdOCrDAciRtsFQ'
	return config
})

request.interceptors.response.use(
	response => {

		let res = response.data

		if (res.code === 200 || res.type=="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
			return response
		} else {
			ElMessage.error(!res.msg ? '系统异常' : res.msg)
			return Promise.reject(response.data.msg)
		}

	},
	error => {
		// 获取自己捕获错误返回过来的Result
		if (error.response) {
			if (error.response.data){
				error.massage = error.response.data.msg
			}
		}

		// 401 一般是token问题，过期，或者token无法解析
		if (error.response.status === 401) {
			// 过期后也不会自动清除，要求重新登录顺便将其token清一下
			localStorage.clear()
			// 对于一些token出现问题的进行要求重新登录
			router.push("/login")
		}

		ElMessage.error(error.massage)
		return Promise.reject(error.massage)
	}
)

export default request
